"""
  created by fanxl on 2018/5/13 18:29
"""
from flask import Flask, current_app, request, Request

app = Flask(__name__)

# ctx = app.app_context()
# ctx.push()
# a = current_app
# d = current_app.config['DEBUG']
# ctx.pop()

with app.app_context():
    a = current_app
    d = current_app.config['DEBUG']

# 实现了上下文协议的对象使用with
# 上下文管理器 (实现了__enter__ __exit__两个方法的类就是上下文管理器)
# __enter__ __exit__ 实现了就是实现了上下文协议
# 上下文表达式必须要返回一个上下文管理器 app.app_context()就是上下文表达式


# with open(r'D:/Test/mao.txt') as f:
#     f.read()
# as这里返回的不是上下文管理器，而是__enter__方法返回的对象


class MyResource:
    def __enter__(self):
        print('connect to server')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb:
            print('has exception')
        else:
            print('no exception')
        print('disconnect to server')
        # 返回True的话有异常不会往外抛，返回False有异常情况会继续往外抛异常
        return False

    def query(self):
        print('query data...')


try:
    with MyResource() as resource:
        1 / 0
        resource.query()
except Exception as e:
    print(e)
